using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using RssReader.Data;
using System.Xml.Linq;
using System.Globalization;

namespace RssReader
{
	[MonoTouch.Foundation.Register("ArticlesTableViewController")]
	public partial class ArticlesTableViewController : UITableViewController
	{
		static NSString kCellIdentifier = new NSString ("ArticleCellID");
		Database.ArticlesRow[] AvailableArticles;

		//
		// Constructor invoked from the NIB loader
		//
		public ArticlesTableViewController (IntPtr p) : base(p)
		{
			Title = "Articles";
		}

		public ArticlesTableViewController () : base()
		{
			Title = "Articles";
		}

		//
		// The data source for our TableView
		//
		class DataSource : UITableViewDataSource
		{
			ArticlesTableViewController tvc;

			public DataSource (ArticlesTableViewController tvc)
			{
				this.tvc = tvc;
			}

			public override int RowsInSection (UITableView tableView, int section)
			{
				return tvc.AvailableArticles.Length;
			}

			public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
			{
				var cell = tableView.DequeueReusableCell (kCellIdentifier);
				if (cell == null) {
					cell = new UITableViewCell (UITableViewCellStyle.Default, kCellIdentifier);
					cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
				}
				Database.ArticlesRow article = tvc.AvailableArticles[indexPath.Row];
				cell.TextLabel.MinimumFontSize = 12f;
				cell.TextLabel.AdjustsFontSizeToFitWidth = true;
				if(article.IsRead=="Y")
					cell.TextLabel.TextColor = UIColor.Purple;
				else
					cell.TextLabel.TextColor = UIColor.Blue;
				cell.TextLabel.Text = article.Title;
				// Customize the cell here...
				cell.TextLabel.Lines=1;
				cell.TextLabel.LineBreakMode = UILineBreakMode.TailTruncation;
				return cell;
			}
		}

		//
		// This class receives notifications that happen on the UITableView
		//
		class TableDelegate : UITableViewDelegate
		{
			ArticlesTableViewController tvc;

			public TableDelegate (ArticlesTableViewController tvc)
			{
				this.tvc = tvc;
			}

			public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
			{
				tableView.CellAt(indexPath).TextLabel.TextColor= UIColor.Purple;
				tvc.AvailableArticles[indexPath.Row].IsRead = "Y";
				Data.DatabaseTableAdapters.ArticlesTableAdapter adapter = new Data.DatabaseTableAdapters.ArticlesTableAdapter ();
				//adapter.Update (tvc.AvailableArticles[indexPath.Row]);
				DetailsViewController dvc = new DetailsViewController();
				dvc.CurrentArticle=tvc.AvailableArticles[indexPath.Row];
				tvc.NavigationController.PushViewController(dvc,true);
			}
		}

		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			DataBind ();
			TableView.Delegate = new TableDelegate (this);
			TableView.DataSource = new DataSource (this);
		}
		public Database.FeedsRow CurrentFeed { get; set; }
		#region IBindable implementation
		public void DataBind ()
		{
			XDocument rss = XDocument.Load (CurrentFeed.FeedURL);
			Database.ArticlesDataTable dt = new Database.ArticlesDataTable ();
			Data.DatabaseTableAdapters.ArticlesTableAdapter adapter = new Data.DatabaseTableAdapters.ArticlesTableAdapter ();
			adapter.Fill (dt);
			
			
			System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo ("en-US");
			var query = from item in rss.Descendants ("item")
				select new { Title = (string)item.Element ("title"), Link = (string)item.Element ("link"), Description = (string)item.Element ("description"), PubDate = (string)item.Element ("pubDate") };
			
			foreach (var item in query) {
				
				string formattedDate = item.PubDate.Remove (0, 5);
				formattedDate = formattedDate.Substring (0, formattedDate.LastIndexOf (" "));
				if (dt.Count (t => t.FeedID == CurrentFeed.FeedID && t.Link == item.Link)==0)
				{
					//adapter.Insert(CurrentFeed.FeedID, item.Title, "N", item.Link, item.Description, DateTime.ParseExact (formattedDate, "dd MMM yyyy HH:mm:ss", culture, DateTimeStyles.AllowWhiteSpaces));
					dt.AddArticlesRow(CurrentFeed, item.Title, "N", item.Link, item.Description, DateTime.ParseExact (formattedDate, "dd MMM yyyy HH:mm:ss", culture, DateTimeStyles.AllowWhiteSpaces));
				}
			}
			
			
			
			
			Title = CurrentFeed.FeedTitle;
			var allRows = from a in dt where a.FeedID==CurrentFeed.FeedID orderby a.IsRead, a.PubDate descending select a;
			
			AvailableArticles = allRows.ToArray();
		}
		
		#endregion
	}
}
